package net.noday.demo.persistent;

import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import net.noday.demo.domain.Person;

@Repository("personDAO")
public class PersonDAO {

	private JdbcTemplate jdbcTemplate;
	
	@Resource
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void add(Person person) {
		jdbcTemplate.update("insert into person(name) values(?)", 
				new Object[]{person.getName()}, new int[]{java.sql.Types.VARCHAR});
	}
	
	public void update(Person person) {
		jdbcTemplate.update("update person set name=? where id=?", 
				new Object[]{person.getName(),person.getId()}, 
				new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
	}
	
	public Person get(Integer id) {
		return (Person)jdbcTemplate.queryForObject("select * from person where id=?", 
				new Object[]{id}, 
				new PersonRowMapper());
	}
	
	public List<Person> getAll() {
		return (List<Person>)jdbcTemplate.query("select * from person", 
				new PersonRowMapper());
	}
	
	public void delete(Integer id) {
		jdbcTemplate.update("delete from person where id=?", 
				new Object[]{id}, 
				new int[]{java.sql.Types.INTEGER});
	}
}
